<script name='Annex' setup>
import { addAnnexApi, delAnnexApi, delProjectApi, downloadAnnexApi, queryAnnexListApi, downloadAnnexMinioApi } from '@/api/business/project'
import useCommonStore from '@/store/modules/common'
import { saveAs } from 'file-saver'
import { parseTime } from '../../../utils/ruoyi'
import useUserStore from '@/store/modules/user'
const commonStore = useCommonStore()
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { business_annex_type } = proxy.useDict('business_annex_type')
const route = useRoute()

//查询
const queryParams = ref({
    originalName: void 0,
    type: void 0,
    createBy: void 0,
})
const loading = ref(false)
const showSearch = ref(true)

function resetQuery() {
    proxy.resetForm('queryRef')
}

function handleQuery() {
    getAnnexList()
}

//表格
const annexList = ref([])
const ids = ref([])

async function getAnnexList() {
    const { data } = await queryAnnexListApi(route.params.id, queryParams.value)
    annexList.value = data
}
getAnnexList()
function handleUpload() {
    title.value = '上传附件'
    open.value = true
}
async function handleDownload(row) {
    let data
    if (userStore.storageMethod === 'local') {
        data = await downloadAnnexApi(row.uploadId)//本地下载
    } else if (userStore.storageMethod === 'minio') {
        // data = await downloadAnnexMinioApi(row.url)//minio下载
        const a = document.createElement('a');
        a.href = row.url;
        a.download = row.originalName || 'download';
        a.target = '_blank';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        return
    }
    console.log(data, row.originalName, 111111111111111111);

    saveAs(data, row.originalName)
}
function handleDelete(row) {
    const uploadIds = (row.uploadId && [row.uploadId]) || ids.value
    const annexNames = uploadIds.map(uploadId => {
        return annexList.value.find(annex => annex.uploadId === uploadId).originalName
    })

    proxy.$modal.confirm('是否确认删除附件 ' + `${annexNames.join(', ')}`).then(function () {
        return delAnnexApi(uploadIds)
    }).then(() => {
        handleQuery()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.uploadId)
}

//表单
const open = ref(false)
const title = ref('上传附件')
const form = ref({
    type: '0',
    fileList: []
})
const rules = ref({
    type: [{ required: true, message: '附件类型不能为空', trigger: 'change' }],
    fileList: [{ required: true, message: '附件不能为空', trigger: 'change' }]
})



async function submitForm() {
    await proxy.$refs['annexRef'].validate()
    const formData = new FormData()
    formData.append('type', form.value.type)
    formData.append('file', form.value.fileList[0].raw)


    await addAnnexApi(route.params.id, formData)
    proxy.$modal.msgSuccess('新增成功')
    cancel()
    handleQuery()
}
function cancel() {
    reset()
    open.value = false
}
function reset() {
    form.value = {
        type: '0',
        fileList: []
    }
    proxy.resetForm('annexRef')
}
</script>

<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams">
            <el-form-item label="附件名称" prop="originalName">
                <el-input v-model="queryParams.originalName" clearable placeholder="请输入附件名称" style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="附件类型" prop="type">
                <el-select v-model="queryParams.type" clearable placeholder="附件类型" style="width: 200px">
                    <el-option v-for="item in business_annex_type" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传人" prop="createBy">
                <el-select v-model="queryParams.createBy" clearable placeholder="上传人" style="width: 200px">
                    <el-option v-for="item in commonStore.userList" :key="item.userId" :label="item.nickName"
                        :value="item.userId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['business:annex:add']" icon="Plus" plain type="primary" @click="handleUpload">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['business:annex:remove']" :disabled="!ids.length" icon="Delete" plain
                    type="danger" @click="handleDelete">删除
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="handleQuery"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="annexList" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <!--            <el-table-column align="center" label="项目名称" prop="project.projectName" />-->
            <el-table-column align="center" label="附件名称" prop="originalName"> </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime">
                <template #default="{ row }">
                    <span>{{ parseTime(row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="文件类型" prop="ext"> </el-table-column>
            <el-table-column align="center" label="附件类型" prop="type">
                <template #default="{ row }">
                    <span>{{business_annex_type.find(type => row.type === type.value)?.label}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="上传人" prop="user.nickName"> </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                <template #default="{ row }">
                    <el-button v-hasPermi="['business:annex:edit']" icon="Edit" link type="primary"
                        @click="handleDownload(row)">下载
                    </el-button>
                    <el-button v-hasPermi="['business:annex:remove']" icon="Delete" link type="primary"
                        @click="handleDelete(row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加或修改附件对话框 -->
        <el-dialog v-model="open" :title="title" append-to-body width="500px" @close='cancel'>
            <el-form ref="annexRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="附件类型" prop="type">
                    <el-select v-model="form.type" placeholder="附件类型" style="width: 200px">
                        <el-option v-for="item in business_annex_type" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="附件" prop="fileList">
                    <el-upload ref="uploadRef" :limit="1" v-model:file-list="form.fileList" action style="width: 100%;"
                        :auto-upload="false" :drag="!form.fileList.length">
                        <el-icon v-show="!form.fileList.length" class="el-icon--upload"><upload-filled /></el-icon>
                        <div v-show="!form.fileList.length" class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped></style>
